<?php

namespace App\Console\Commands;


use App\Models\News;
use App\Models\NewsDesc;
use App\Models\SiteCate;
use Illuminate\Console\Command;
use App\Service\Dir;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\DB;


class UpdateNewsCommand extends Command
{
    //  更新文章信息（可以重复执行）
    //  sudo -u www  php artisan command:update-news id
    //  sudo -u www php /www/wwwroot/slh/laravel.test/artisan command:update-news id
    //  sudo -u www php /www/wwwroot/shenlanhui/laravel/artisan command:update-news id


    protected $signature   = 'command:update-news {id?} ';
    protected $description = '更新文章信息';

    public function __construct()
    {
        parent::__construct();
    }

    // 执行的命令
    public function handle()
    {
        // 设置参数
        $id  = $this->argument('id');
        $num = 100;
        $max = 100000;

        /*$str = "Wistron&#39;s  &#39;  Huawei's   revenue in No'vember \"increased\" & 24.6% year-on-year";
        var_dump($str);
        var_dump(html_entity_decode($str));
        var_dump(htmlspecialchars($str));
        var_dump(html_entity_decode(htmlspecialchars($str)));
        die;*/

        // 修改文章标题
        //$this->line('修改文章标题~~~~~');
        //$this->toUpdateTitle($id, $num, $max);


        // 修改文章的链接
        //$this->line('修改文章内容~~~~~');
        //$this->toUpdateContent($id, $num, $max);

        // 匹配文章栏目
        $cateKeywords = $this->getCateKeywords('en_keyword');

        // 修改文章的链接
        //$this->line('修改文章的链接~~~~~');
        //$this->toUpdateLink($id, $num, $max);


        $this->comment('执行完成！');

        return true;
    }


    // 匹配文章到栏目
    protected function toUpdateCate($cateKeywords, $id = 0, $number = 100, $max = 0)
    {
        $lists = $this->getNews($id, $number, $max);
        // 获取文章详情
        $lists = (new NewsDesc())->whereIn('news_id', array_column($lists, 'id'))->get()->toArray();
        $count = count($lists);
        $this->comment('获取到的文章数量：'.$count);
        if($lists){
            $cates = $newsIds = [];
            foreach($lists as $_row){
                // 根据内容匹配栏目关键词
                $content   = $_row['en_content'];
                $news_id   = $_row['news_id'];
                $newsIds[] = $news_id;
                foreach($cateKeywords as $_keyword => $_cateId){
                    // 标签：关键词
                    $_keyword = trim($_keyword);
                    // 如果没有这个关键词
                    if(strpos($content, $_keyword) === false){
                        continue;
                    }

                    // 如果这个栏目以及匹配了  则不在匹配这个栏目
                    if(isset($cates[$news_id]) && in_array($_cateId, $cates[$news_id])){
                        continue;
                    }

                    // 一篇文章多个栏目
                    $cates[$news_id][] = $_cateId;
                }
            }

            // TODO
            //  查询 $newsIds 所在的栏目
            //  将 $cates 不存在的栏目 保存到数据库中
        }

        // 继续
        $this->sqlLog();
        if($count == $number){
            $this->line('        继续获取文章，最小id为：'.$max);
            $this->toUpdateContent($id, $number, $max);
        }

        return true;
    }

    // 修改文章标题  在这里是修改文章的实体符号
    protected function toUpdateTitle($id = 0, $number = 100, $max = 0)
    {
        $lists = $this->getNews($id, $number, $max);
        $count = count($lists);
        $this->comment('获取到的文章数量：'.$count);
        if($lists){
            foreach($lists as $_row){
                $max      = max($max, $_row['id']);
                $en_title = html_entity_decode(str_replace('&#39;', "'", $_row['en_title']));
                (new News())->where('id', $_row['id'])->update(['en_title' => $en_title]);
            }
        }

        // 继续
        $this->sqlLog();
        if($count == $number){
            $this->line('        继续获取文章，最小id为：'.$max);
            $this->toUpdateTitle($id, $number, $max);
        }

        return true;
    }

    // 修改文章内容  在这里是修改文章的实体符号
    protected function toUpdateContent($id = 0, $number = 100, $max = 0)
    {
        $lists = $this->getNews($id, $number, $max);
        // 获取文章详情
        $lists = (new NewsDesc())->whereIn('news_id', array_column($lists, 'id'))->get()->toArray();
        $count = count($lists);
        $this->comment('获取到的文章数量：'.$count);
        if($lists){
            foreach($lists as $_row){
                $max        = max($max, $_row['news_id']);
                $en_content = html_entity_decode(str_replace('&#39;', "'", $_row['en_content']));
                DB::table('news_desc')->where('news_id', $_row['news_id'])->update(['en_content' => $en_content]);
            }
        }

        // 继续
        $this->sqlLog();
        if($count == $number){
            $this->line('        继续获取文章，最小id为：'.$max);
            $this->toUpdateContent($id, $number, $max);
        }

        return true;
    }


    // 更新文章的链接
    protected function toUpdateLink($id = 0, $number = 100, $max = 0)
    {
        $lists = $this->getNews($id, $number, $max);
        $count = count($lists);
        $this->comment('获取到的文章数量：'.$count);
        if($lists){
            foreach($lists as $_row){
                $max  = max($max, $_row['id']);
                $link = atwArticleLink($_row['en_title'], $_row['id']);
                DB::table('news')->where('id', $_row['id'])->update(['link' => $link]);
            }
        }

        // 继续
        $this->sqlLog();
        if($count == $number){
            $this->line('        继续获取文章，最小id为：'.$max);
            $this->toUpdateLink($id, $number, $max);
        }

        return true;
    }

    // 获取文章
    protected function getNews($id = 0, $number = 100, $max = 0)
    {
        if($id){
            $lists = (new News())->where('id', $id)->get()->toArray();
        } else{
            //$lists = (new News())->where('link', '')->where('id', '>', $max)->limit($number)->get()->toArray();
            $lists = (new News())->where('id', '>', $max)->limit($number)->get()->toArray();
        }

        return $lists;
    }

    // 获取所有的栏目 组合关键词列表
    //  $field:对比的字段，这里默认为中文
    protected function getCateKeywords($field = 'en_keyword')
    {
        $cateDb = new SiteCate();
        $cates  = $cateDb->isCache(true)->getAll(['status' => 1]);
        $cates  = is_object($cates) ? $cates->toArray() : $cates;

        // 整理
        $lists = [];
        foreach($cates as $_cate){
            $keywords = explode(',', $_cate[$field]);
            foreach($keywords as $_keyword){
                if(empty($_keyword)){
                    continue;
                }
                // 组合
                $lists[$_keyword] = $_cate['id'];
            }
        }

        return $lists;
    }


    // sql日志
    protected function sqlLog()
    {
        // 保存sql语句到日志中
        /*$queries = DB::getQueryLog();
        foreach($queries as $query){
            $sql = str_replace('?', '\'%s\'', $query['query']);
            $sql = vsprintf($sql, $query['bindings']);
            $log = 'SQL: '.$sql.'; [RunTime:'.$query['time'].'ms]';
            Log::info($log);
        }*/

        // 是否内存
        DB::flushQueryLog();
    }

}

